<!--
*@Author: QWP
*@Description: 应急方案
*@Date: 2024-07-31 17:02:17
-->
<template>
  <a-layout class="f-h-100">
    <a-layout-header class="u-knowledge-header" style="">
      <div
        class="f-flex-column"
        style="width: 100%; height: 100%; justify-content: flex-end"
      >
        <a-row class="f-font-family u-span-title" justify="center">
          <a-popover
            :arrow="false"
            placement="bottom"
            v-model:open="showTip"
            trigger="contextmenu"
          >
            <template #content>
              <p>Content</p>
              <p>Content</p>
            </template>
            <a-input-search
              style="width: 80%"
              enter-button
              size="large"
              v-model:value="searchF.model.keywords"
              @search="onSearchEnter"
            >
              <template #enterButton>
                <a-button>Custom</a-button>
              </template>
            </a-input-search>
          </a-popover>
        </a-row>
        <a-row class="f-font-family u-span-title" justify="center">
          <a-space style="width: 80%; overflow: hidden">
            <div style="width: 70px">
              <b class="f-margin-r6">搜索历史</b>
            </div>
            <a-tag
              v-for="item in history"
              closable
              @click="(searchF.model.keywords = item), getSearch(1, 'tag')"
              @close="closeHis(item)"
            >
              {{ item }}
            </a-tag>
          </a-space>
        </a-row>
      </div>
    </a-layout-header>
    <a-layout class="f-h-100">
      <u-table-header>
        <a-row justify="space-between" class="f-padding-b10">
          <a-tag
            :color="currentType == item.value ? 'rgba(24,144,255,0.2)' : '#fff'"
            :bordered="false"
            v-for="item in srorts"
            style="padding: 6px 16px; cursor: pointer"
            @click="(currentType = item.value), getSearch(1, 'tag')"
          >
            <u-icon-font
              :type="item.icon"
              style="padding-right: 6px; font-size: 16px"
            ></u-icon-font>
            <span style="font-size: 14px; color: #333333">
              {{ item.label }}
            </span>
          </a-tag>
          <a-space size="middle">
            <u-icon-button itype="add" @click="showUpload = true">
              新增上传
            </u-icon-button>
            <u-icon-button itype="delete" @click="deleteFun('all')">
              批量删除
            </u-icon-button>
          </a-space>
        </a-row>
      </u-table-header>
      <u-table-content style="height: 100%; overflow: auto">
        <u-table
          :columns="columns"
          :data="tabData"
          :loading="loading"
          :scroll="{ y: 'calc(100vh - 430px)' }"
          v-model:pagination="pagenation"
          @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
          @change="getSearch('', 'tag')"
        ></u-table>
      </u-table-content>
    </a-layout>
  </a-layout>

  <Edit
    v-model:open="showUpload"
    title="应急预案新增"
    width="800px"
    :type="currentType"
    @success="
      showUpload = false;
      getSearch('', 'tag');
    "
  ></Edit>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, provide } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { PlusOutlined } from '@ant-design/icons-vue';
import { urlFile, isValue } from '@/util/common';
import { cloneDeep } from 'lodash';
import { storeTo } from 'pinia';
import { Button, Space, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import UIconFont from '@/components/common/iconfont/IconFont.vue';
import * as schemeApi from '@/service/emergency/scheme';
import { usePreview, useDownload } from '@/hooks/useFile';
import { alertC, messageC } from '@/util/common';
import { Popconfirm } from 'ant-design-vue';
import Edit from './Edit.vue';
import { useBaseStore, useLoginStore } from '@/store';
import { storeToRefs } from 'pinia';
const { userInfo } = storeToRefs(useLoginStore());
let siderCurrent = ref<string>('');
// { label: '应急专栏', icon: 'icon-guanzhuqiyeguanli' },
const siderData = ref<any[]>();
const siderClick = data => {
  siderCurrent.value = data.label;
};

const initLoading = ref<boolean>(false);
const loading = ref<boolean>(false);

const currentType = ref<string>('');
const srorts = [
  { label: '全部', value: '', icon: 'icon-quanbu' },
  { label: '地震', value: '地震', icon: 'icon-a-dizhen1' },
  { label: '地质', value: '地质', icon: 'icon-dizhi' },
  { label: '洪涝', value: '洪涝', icon: 'icon-honglao' },
  { label: '森林草原', value: '森林草原', icon: 'icon-senlincaoyuan' },
  { label: '火灾', value: '火灾', icon: 'icon-huozai' },
  { label: '危化', value: '危化', icon: 'icon-weihuapin' },
  { label: '矿山', value: '矿山', icon: 'icon-kuangshan' },
  { label: '其他', value: '其他', icon: 'icon-qita' },
];
provide('srorts', srorts);

// 查询
const searchF = reactive({
  model: {
    keywords: '',
  },
});
const searchEl: Array<_IFormEl> = [
  {
    label: '模糊查询',
    key: 'option',
    element: 'input',
    col: { span: 5 },
    formItemProps: { labelWidth: '80px', wrapperCol: 24 },
    componentProps: { placeholder: '搜索知识库标题或内容' },
  },
];

// 列表筛选
let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: total => `共 ${total} 条`,
});

// 切割字符串
function lengthCutting(str, num) {
  let strArr = [];

  for (let i = 0; i < str.length; i += num) strArr.push(str.slice(i, i + num));
  return strArr;
}

// 列表
const tabSelData = ref<any[]>([]);
const tabData = ref<any[]>([]);
let columns: Array<TableColumnProps> = reactive([
  {
    dataIndex: 'index',
    title: '序号',
    width: 50,
    align: 'center',
    customRender: ({ index }) => (index += 1),
  },
  {
    dataIndex: 'emergencyPlanName',
    title: '标题',
    width: 300,
    customRender: ({ text, record }) => {
      return h(
        Button,
        { type: 'link', 
          title: text,
          class: 'u-text-over-ellipsis', onClick: () => usePreview(record['fileUrl'] || record['filepath']) },
        () => text
      );
    },
  },
  {
    dataIndex: 'emergencyPlanType',
    title: '分类',
    width: 240,
    align: 'center',
  },
  {
    dataIndex: 'emergencyPlanNo',
    title: '文件编号',
    width: 240,
    align: 'center',
  },
  {
    dataIndex: 'updatetime',
    title: '上传时间',
    width: 240,
    align: 'center',
    customRender: ({ text }) => {
      return (text || '').split(' ')[0];
    },
  },
  {
    dataIndex: 'do',
    title: '操作',
    width: 160,
    align: 'center',
    customRender: ({ text, record }) => {
      return h(
        Space,
        {
          size: 'large',
          class: 's-text-color1 f-font-bold f-cursor f-font-size18',
        },
        () => [
          h(UIconFont, {
            type: 'icon-a-lujing12',
            onClick: () => useDownload(record),
          }),
          h(
            Popconfirm,
            {
              title: '您确定要删除吗？',
              onConfirm: () => {
                if (
                  userInfo.value['extra']['roles']['1'] &&
                  userInfo.value['extra']['roles']['1'].length > 0
                ) {
                  deleteFun('single', record);
                } else {
                  alertC('非系统管理员不能删除！', 'warning');
                }
              },
            },
            () => [h(UIconFont, { type: 'icon-shanchu' })]
          ),
        ]
      );
    },
  },
]);

const showTip = ref<boolean>(false);
const history = ref<string[]>();
const historyLen = computed(() =>
  cloneDeep(history.value).reverse().slice(0, 5)
);

onMounted(() => {
  history.value = JSON.parse(localStorage.getItem('_s_his') || '[]').filter(
    item => isValue(item)
  );

  getSearch();
});

// type 来源位置
const getSearch = (current?: number, type?: string) => {
  if (current == 1) {
    pagenation.current = current;
  }
  const tsearchF = cloneDeep(searchF);
  // 点击类型的查询
  if (type == 'tag') {
    tsearchF.model.keywords = currentType.value;
  }
  tsearchF.size = pagenation.pageSize;
  tsearchF.current = pagenation.current;
  loading.value = true;
  schemeApi
    .page(tsearchF)
    .then(res => {
      loading.value = false;
      if (res.code == 0) {
        tabData.value = res.data.records;
        pagenation.total = res.data.total;
      }
    })
    .catch(() => (loading.value = false));
};

/**
 *@Author: QWP
 *@Description: 查询，回车
 *@Date 2024-08-27 09:26
 */
const onSearchEnter = val => {
  getSearch(1);
  if (!history.value.some(i => i == val) && val) {
    history.value.push(val);
    localStorage.setItem('_s_his', JSON.stringify(history.value));
  }
};

/**
 *@Author: QWP
 *@Description: 删除搜索历史
 *@Date 2024-08-27 09:26
 */
const closeHis = val => {
  history.value = history.value.filter(i => i != val);
  localStorage.setItem('_s_his', JSON.stringify(history.value));
};

// 上传弹窗
const showUpload = ref<boolean>(false);

// 删除
const deleteFun = async (type?: string = 'all', record?: object) => {
  if (type == 'all') {
    if (tabSelData.value.length == 0) {
      messageC('请先选择需要删除的数据!');
      return;
    }
  }
  const data = type == 'all' ? tabSelData.value : [record];
  loading.value = true;
  try {
    const res = await schemeApi.del({ ids: data.map(i => i.keyid).join() });
    if (res.code == 0) {
      messageC(res.msg, 'success');
      getSearch('', 'tag');
    } else {
      messageC(res.msg, 'error');
    }
  } catch (error) {}
  loading.value = false;
};
</script>

<style lang="scss" scoped>
:deep(.u-knowledge-header) {
  margin-bottom: 16px;
  height: 120px;
  padding: 0;
  background: url('./../../../../assets/knowledge/headerBg.png');
  background-size: 100% 100%;
}

.u-span-title {
  font-weight: 600;
  font-size: var(--font-size-level-2);
  color: #333333;
}

.u-span-sider-span {
  font-weight: 400;
  font-size: var(--font-size-level-1);
  color: #333333;
}

.u-sider-icon {
  font-size: 18px;
  color: #aaa;
}

.u-sider-active {
  background: rgba(24, 144, 255, 0.2);
  border-radius: 0px 0px 0px 0px;
  font-weight: 400;
  font-size: var(--font-size-level-1);

  .u-span-sider-span {
    color: #1890ff;
  }

  .u-sider-icon {
    color: #1890ff;
  }
}

:deep(.u-knowledge-list) {
  // .ant-spin-container {
  //   .ant-row {
  //     div {
  //       height: 200px
  //     }
  //   }
  // }
  .u-list-item {
    padding: 0;
    height: max-content;
    background: #ffffff;
    box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;

    .u-list-item-label {
      padding: 11px 20px;

      .u-title {
        display: inline-block;
        max-width: 100%;
        font-weight: 400;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        font-size: var(--font-size-level-1);
        color: #333333;
      }

      .u-desc {
        font-weight: 400;
        font-size: var(--font-size-level-0);
        color: #666666;
      }
    }
  }
}

:deep(.u-list-item-active) {
  border-radius: 8px;
  // border: 1px solid #1890FF;
  box-shadow: 0px 0 4px 0px #1890ff;
  // box-shadow: unset
}
</style>
